<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <div class="dialog-table">
      <page-filter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-button>
          <div class="dialog-table-header">
            <div class="header-left">
              <div class="lable">产品名称：{{ info.commonName }}</div>
              <div class="lable">生产批号：{{ info.batchNumber }}</div>
            </div>
            <div class="header-right">
              <div class="scan-groups">
                <el-input
                  v-model="filterInfo.sacnCode"
                  :clearable="true"
                  placeholder="请扫码二维码/个体码"
                  @keyup.enter.native="sacn"
                  @input="(e) => (filterInfo.sacnCode = validSe(e))"
                >
                  <el-select v-model="selectedScanValue" #prepend>
                    <el-option
                      v-for="item in selectedScanOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-input>
              </div>
            </div>
          </div>
          <div>
            <el-button style="margin-right: 10px" @click="changeNumberAll(true)"
              >一键填充数量</el-button
            >
            <el-button @click="changeNumberAll(false)">一键清空</el-button>
          </div>
        </template>
      </page-filter>
    </div>
    <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
      <DialogTable
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        ref="depotTable"
        v-model:data="tableInfo.data"
        :api="api"
        :pager="false"
        :tabIndex="true"
        :checkBox="false"
        :listen-height="false"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
      >
        <template v-slot:col-qty="scope">
          <el-input-number
            v-model="scope.row.qty"
            controls-position="right"
            style="width: 100px"
            :precision="0"
            v-enterNumber
            :disabled="scope.row.totalStockQty === 0"
            :max="scope.row.totalStockQty"
            :min="0"
          ></el-input-number>
        </template>
      </DialogTable>
    </el-form>
  </page-dialog>
</template>

<script setup name="IndividualDetails">
import PageDialog from "@/components/PageDialog/index";
import PageFilter from "@/components/PageFilter/index";
import { useExportDetailExtGetUnityData } from "@/api/use";
import DialogTable from "@/components/DialogTable/index";

const { proxy } = getCurrentInstance();
const emit = defineEmits();

const props = defineProps({
  api: {
    type: Function,
    default: useExportDetailExtGetUnityData,
  },
  showDialog: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {};
    },
  },
  info: {
    type: Object,
    default: function () {
      return {};
    },
  },
});

const selectedScanOptions = [
  {
    label: "增加",
    value: "1",
  },
  {
    label: "减少",
    value: "2",
  },
];

const selectedScanValue = ref("1");
const scanInput = ref("");
const selectRow = ref("");
const isReturnShow = ref(true);

const filterInfo = reactive({
  query: {
    sort: "create_time desc",
    ...props.query,
  },
  sacnCode: "",
  list: [{ type: "slot", value: "button" }],
});
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: "个体码", value: "unityCode" },
    { label: "原厂码", value: "factorySubCode" },
    {
      label: "领出仓库存量",
      value: "totalStockQty",
      type: "column",
    },
    {
      label: "单价",
      value: "price",
      type: "column",
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: "出库数量",
      value: "qty",
      type: "slot",
    },
  ],
});
// 弹窗相关
const dialogInfo = reactive({
  title: "选择个体",
  width: "90%",
  btLoading: false,
  btList: [
    { label: "关闭", event: handleClose, show: true },
    { label: "保存", event: handleSave, show: true },
  ],
});

const shows = computed({
  get() {
    return props.showDialog;
  },
  set(newValue) {
    emit("update:showDialog", newValue); // 更新父组件shows
  },
});
watch(
  () => tableInfo.data,
  (val) => {
    if (val.length > 0) {
      if (isReturnShow.value) {
        returnShow();
        isReturnShow.value = false;
      }
    }
  }
);

function getList() {
  tableInfo.refresh = Math.random();
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false;
  isReturnShow.value = true;
  emit("reset");
}
function sumArr(arr) {
  let sum = 0;
  arr.map((i) => {
    sum += Number(i.qty);
  });
  return sum;
}
function handleSave() {
  let list = tableInfo.data.filter((item) => item.qty > 0);
  if (!list.length) {
    proxy.$message({
      duration: 3500,
      type: "warning",
      showClose: true,
      message: "出库数量不能全为空或0",
    });
    return;
  }
  const qtyTotal = sumArr(list);
  const param = {
    ...props.info,
    exportQty: qtyTotal,
    details: [...list],
  };
  emit("callback", param);
  handleClose();
  isReturnShow.value = true;
}
function sacn() {
  const code = filterInfo.sacnCode;
  if (!code) {
    proxy.$message({
      duration: 3500,
      type: "warning",
      showClose: true,
      message: "请扫码二维码/个体码",
    });
    return;
  }
  const codeIndex = tableInfo.data.findIndex(
    (value) =>
      value.code === code ||
      value.unityCode === code ||
      value.factorySubCode === code
  );
  if (codeIndex !== -1) {
    let qty = tableInfo.data[codeIndex].qty ? tableInfo.data[codeIndex].qty : 0;
    if (selectedScanValue.value === "1") {
      if (props.info.codeType !== "unique") {
        tableInfo.data[codeIndex]['qty'] = qty + 1
      } else {
        tableInfo.data[codeIndex]['qty'] = qty
      }
    } else if (selectedScanValue.value === "2") {
      if (props.info.codeType !== "unique") {
        tableInfo.data[codeIndex]['qty'] =  qty > 0 ? (qty -= 1) : (qty = 0)
      } else {
        tableInfo.data[codeIndex]['qty'] =  0
      }
    }
    filterInfo.sacnCode = "";
    return;
  } else {
    proxy.$message({
      message: "该领用申请单中没有你要领用的产品",
      type: "warning",
      duration: 3500,
      showClose: true,
    });
    filterInfo.sacnCode = "";
    return;
  }
}
function returnShow() {
  if (props.info.detailExtVOS && props.info.detailExtVOS.length > 0) {
    tableInfo.data.forEach((row) => {
      row['qty'] = 0
      props.info.detailExtVOS.forEach((item) => {
        if (item.depotExtId === row.depotExtId) {
          row['qty'] = item.qty
        }
      });
    });
  }
}
function changeNumberAll(isAll) {
  if (isAll) {
    tableInfo.data.forEach((row) => {
      row.qty = row.totalStockQty || 0;
    });
  } else {
    tableInfo.data.forEach((row) => {
      row.qty = 0;
    });
  }
}
</script>

<style scoped lang="scss">
:deep(.filter-item) {
  width: 100%;
}
.text-style {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
